import config from './config.js'
import utils from './utils.js'
import Toast from '../dist/toast/toast';

const tips = {
  1: '抱歉，出现了一个错误'
};

let needLoadingRequestCount = 0 // 需要loading的请求数量

class HTTP {
  upload({
    url,
    filePath, //需要上传的本地文件路径
    fileType = 'img', //上传的文件类型 文件类型 目前有 img,voice,video默认为img
    isShowLoading = true
  }) {
    return new Promise((resolve, reject) => {
      // 显示loading
      if (isShowLoading) {
        wx.showLoading({
          title: '上传中',
          mask: true
        })
      }
      wx.uploadFile({
        url: config.baseUrl + url,
        filePath: filePath,
        name: 'file',
        formData: {
          type: fileType
        },
        header: {
          'token': wx.getStorageSync('token')
        },
        success: (res) => {
          wx.hideLoading();
          console.log(res);

          if (res.statusCode !== 200) {
            reject(res.errMsg);
            return
          }
          if (!res.data) {
            reject('error!');
            return
          }
          let data = res.data;
          if (typeof (res.data) == 'string') {
            data = JSON.parse(res.data)
          }
          if (data.status !== 'ok') {
            if (data.code != 2007) {
              // token失效
            }
            if (data.msg) {
              reject(data.msg);
              return
            }
            reject('error!')
            return
          }
          if (!data.res) {
            reject('error!');
            return
          }
          console.log(data.res);
          resolve(data.res);
        },
        fail: (err) => {
          wx.hideLoading();
          reject(err.errMsg);
        }
      })
    })
  }

  request({
    url, // 请求url接口
    data = {}, // 请求参数数据
    method = 'POST', // 请求方式
    isJavaRequest = false, // 是否为 java 请求接口，默认为 false
    isShowLoading = true, // 是否显示loading，默认为 true
    isShowerrMsg = true, // 是否提示errMsg信息，默认为 true
    isNeedResponseTime = false, // 是否需要响应时间，默认为 false
    isTempToken = false, //是否使用临时Token
  }) {
    return new Promise((resolve, reject) => {
      this._request(url, resolve, reject, data, method, isJavaRequest, isShowLoading, isShowerrMsg, isNeedResponseTime,isTempToken)
    })
  }

  _request(
    url,
    resolve,
    reject,
    data = {},
    method = 'POST',
    isJavaRequest = false,
    isShowLoading = true,
    isShowerrMsg = true,
    isNeedResponseTime = false,
    isTempToken = false
  ) {
    let base_url   = isJavaRequest ? config.javaUrl : config.baseUrl;
    let dataByJson = isJavaRequest ? JSON.stringify(data) : data;
    let log    = false;
    let startTime = 0;
    let token  = wx.getStorageSync('token');
    let tToken = wx.getStorageSync('t_token');
    if(!(token && token.length > 5) && isTempToken && tToken){
      token = tToken;
    }
    // 显示loading
    if (isShowLoading) {
      this._show_loading()
    }
    if (utils.debugTime > new Date().getTime()) {
      startTime = new Date().getTime();
      log = true;
    }
    wx.request({
      url: base_url + url,
      method: method,
      data: dataByJson,
      header: {
        'content-type': 'application/json',
        'token': token
      },
      success: (res) => {
        if (log === true) {
          utils.log('地址:', url, '参数:', data, '响应:', res,'耗时：',(new Date().getTime() - startTime));
        }
        // 隐藏 loading
        if (isShowLoading) {
          this._hide_loading();
        }
        wx.hideLoading();
        const status = res.data.status;
        if (status === 'ok') {
          if (isNeedResponseTime) {
            res.data.res.tm = res.data.tm;
            resolve(res.data.res)
          } else {
            resolve(res.data.res)
          }
        } else {
          // 不为 java 请求接口，并且错误码为 2007，则需要登录
          if (res.data.code === 2007) {
            let app = getApp();
            // 账号认证错误时自动弹出登录界面
            app.globalData.userInfo = null;
            app.globalData.encryptKey = null;
            utils.cache_remove('encryptKey');
            utils.cache_remove('token');
            utils.cache_remove('_uInfo');
            utils.setToken('');
            let pages = getCurrentPages();
            let page = pages[pages.length - 1];
            if (page.route !== 'pages/home/index/index') {
              page.setData({
                initUser: false,
                openLogin: true,
              });
            }
          } else {
            if (!isShowerrMsg) {
              reject(res.data)
              return
            }
            if (res.data.code != 2030) {
              const errMsg = res.data.msg || '未知错误'
              this._show_error(errMsg);
              console.log('接口报错：', url, dataByJson, res);
            }
          }
          reject(res.data)
        }
      },
      fail: (err) => {
        console.log('请求日志 err：', url, err);
        reject(err);
        // 隐藏loading
        // if (isShowLoading) {
        //   this._hide_loading()
        // }
        Toast.clear();
        wx.hideLoading();
        // this._show_error('网络异常，请求失败！')
      },
      complete: (err) => {
        utils.trackPut({
          actionType: 2,
          actionName: url,
          actionPara: data,
        });
      }
    })
  }

  // 显示loading
  _show_loading() {
      Toast.loading({
        message: '加载中....'
      });
      setTimeout(function () {
        Toast.clear();
      }, 3000);
  }

  // 隐藏loading
  _hide_loading() {
    this._close_loading()
  }

  // 关闭loading
  _close_loading() {

    Toast.clear()
    wx.hideLoading()
  }

  _show_error(msg) {
    Toast({
      type: 'text',
      position: 'bottom',
      message: msg,
      duration: 2000
    })
  }

  _error_handle(status, other) {
    switch (status) {
      case 2007:
        console.log('自动清除token');
        wx._remove_cache('token');
        wx._remove_cache('_uInfo');
    }
  }

  _remove_cache(key) {
    wx.removeStorageSync(key);
    wx.removeStorageSync(key + config.cache_fix);
  }
}

export {
  HTTP
}
